<?php
// Made by RockerMONO (Nick)
// thanks a ton to danopia for loops and other adjustments to the code!!

if(cmd('brainfuck')){
	$textToSend = '';
	$brainfuck = Array();
	$bfPointer = 0;
	$bfSize = 30000;
	$eLoop = 0;
	for($i = 0; $i < $bfSize; $i++){
		$brainfuck[$i] = 0;
	}
	for($i = 0; $i < strlen($msg_params); $i++){
		if($eLoop > 10000){
			$textToSend = 'Error, endless loop found in program!';
			break;
		}
		$eLoop++;
		$bfItem = $msg_params[$i];
		switch($bfItem){
			case '+':
				if ($brainfuck[$bfPointer] < 255) {
					$brainfuck[$bfPointer]++;
				} else {
					$brainfuck[$bfPointer] = 0;
				}
				break;
			case '-':
				if ($brainfuck[$bfPointer] > 0) {
					$brainfuck[$bfPointer]--;
				} else {
					$brainfuck[$bfPointer] = 255;
				}
				break;
			case '[':
				if ($brainfuck[$bfPointer] == 0){
					$loopDepth = 0;
					for($j=$i+1;$j<strlen($msg_params);$j++){
						if ($msg_params[$j]==']') {
							if ($loopDepth == 0) {
								$i = $j;
								break;
							}else{
								$loopDepth--;
							}
						} else if ($msg_params[$j]=='[') {
							$loopDepth++;
						}
					}
				}
				break;
			case ']':
				if ($brainfuck[$bfPointer] != 0)
				{
					$loopDepth = 0;
					for($j=$i-1;$j>=0;$j--)
					{
						if ($msg_params[$j]=='[') {
							if ($loopDepth == 0) {
								$i = $j;
								break;
							}else{
								$loopDepth--;
							}
						} else if ($msg_params[$j]==']') {
							$loopDepth++;
						}
					}
				}
				break;
			case '.':
				$textToSend.=chr($brainfuck[$bfPointer]);
				break;
			case ',':
				$textToSend='Error, input can not be used!';
				break;
			case '>':
				if($bfPointer>$bfSize){
					$textToSend='Error, no more allocated memory!';
					break;
				}
				$bfPointer++;
				break;
			case '<':
				if ($bfPointer > 0) $bfPointer--;
				break;
		}
	}
	$textToSend=str_replace(chr(0),"[0x00]",$textToSend);
	$textToSend=str_replace(chr(7),"[0x07]",$textToSend);
	$textToSend=str_replace(chr(13),"[0x13]",$textToSend);
	$textToSend=str_replace(chr(10),"[0x10]",$textToSend);
	if(!empty($textToSend)) reply($textToSend);
}
?>